import pandas as pd
import numpy as np
import os
import logging
from pyproj import Transformer

class CoordinateConverter:
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.INFO)
        
    def transform_coordinates(self, csv_path, src_epsg, dest_epsg):
        """转换CSV文件中的坐标并保存新文件"""
        try:
            df = pd.read_csv(csv_path)
            transformer = Transformer.from_crs(f"EPSG:{src_epsg}", f"EPSG:{dest_epsg}")
            
            # 转换坐标（使用对调X/Y顺序，通过正确的EPSG代码处理坐标系差异）
            lat, lon = transformer.transform(df['Y'].values, df['X'].values)
            
            # 检查并处理无效坐标
            valid_mask = np.isfinite(lon) & np.isfinite(lat)
            if not np.all(valid_mask):
                invalid_count = np.sum(~valid_mask)
                self.logger.warning(f"检测到{invalid_count}个无效坐标点，已自动过滤")
                lon = lon[valid_mask]
                lat = lat[valid_mask]
                df = df[valid_mask].copy()
                
            # 确保转换后的经纬度顺序正确
            df['Lon'] = lon  # 经度
            df['Lat'] = lat  # 纬度
            
            # 生成新的文件名
            base, ext = os.path.splitext(csv_path)
            transformed_csv = f"{base}_transformed{ext}"
            df.to_csv(transformed_csv, index=False)
            return transformed_csv
        except Exception as e:
            self.logger.error(f"坐标转换失败: {str(e)}")
            return None

    def generate_kml(self, csv_path, output_path):
        """从CSV文件生成KML文件"""
        try:
            df = pd.read_csv(csv_path)
            
            # 检查并过滤无效坐标点
            valid_mask = np.isfinite(df['Lon']) & np.isfinite(df['Lat']) & np.isfinite(df['OffsetElevation'])
            df = df[valid_mask].copy()
            
            with open(output_path, 'w', encoding='utf-8') as f:
                f.write('<?xml version="1.0" encoding="UTF-8"?>\n')
                f.write('<kml xmlns="http://www.opengis.net/kml/2.2">\n')
                f.write('  <Document>\n')
                f.write(f'    <name>航线路径</name>\n')
                f.write('    <Placemark>\n')
                f.write('      <LineString>\n')
                f.write('        <coordinates>\n')
                
                coords = [f"{row.Lon},{row.Lat},{row.OffsetElevation}" for _, row in df.iterrows()]
                f.write('          ' + ' '.join(coords) + '\n')
                
                f.write('        </coordinates>\n')
                f.write('      </LineString>\n')
                f.write('    </Placemark>\n')
                f.write('  </Document>\n')
                f.write('</kml>\n')
            return True
        except Exception as e:
            self.logger.error(f"KML生成失败: {str(e)}")
            return False